package net.lzzy.practices.services;

import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.entities.Chapter;
import net.lzzy.practices.entities.Course;
import net.lzzy.practices.repositonies.ChapterRepository;
import net.lzzy.practices.repositonies.CourseRepository;
import net.lzzy.practices.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * @author m
 */
@Service
public class ChapterServiceImpl  implements  ChapterService{

    private final ChapterRepository repository;
    private final CourseRepository cRepository;

    @Autowired
    public ChapterServiceImpl(ChapterRepository repository, CourseRepository cRepository) {
        this.repository = repository;
        this.cRepository = cRepository;
    }


    @Override
    public List<Chapter> getTeachersChapters(UUID courseId, String token) {
        Course course= cRepository.getById(courseId);
        UUID teacherId=course.getTeacher().getId();
        if(!teacherId.toString().equals(JwtUtil.verifyToken(token))){
            return null;
        }
        return repository.findChaptersByCourseIdOrderByUpdateTime(courseId);
    }

    @Override
    public List<Chapter> getStudentsChapters(UUID courseId, String token) {
        return repository.findChaptersByCourseIdAndOpenOrderByUpdateTimeDesc(courseId,true);
    }

    @Override
    public Chapter getById(UUID chapterId) {
        return repository.findById(chapterId).orElse(null);
    }

    @Override
    public Chapter add(Chapter chapter) {
        return repository.save(chapter);
    }

    @Override
    public Chapter update(Chapter chapter, String token) {
        UUID teacherId=chapter.getCourse().getTeacher().getId();
        if(!teacherId.toString().equals(JwtUtil.verifyToken(token))){
            return null;
        }
        chapter.setUpdateTime(new Date());
        return repository.save(chapter);
    }

    @Override
    public Chapter openCloseChapter(UUID chapterId, boolean open, String token) {
        Chapter chapter=repository.findById(chapterId).orElse(null);
        if(chapter!=null){
            chapter.setOpen(open);
            return update(chapter,token);
        }
        return null;
    }

    @Override
    public Messages remove(UUID courseId, UUID chapterId, String token) {
        Chapter chapter=repository.findById(chapterId).orElse(null);
        if(chapter==null){
            return Messages.WRONG_ID;
        }
        Course course = cRepository.getById(courseId);
        UUID teacherId=course.getTeacher().getId();
        if(!teacherId.toString().equals(JwtUtil.verifyToken(token))){
            return Messages.NO_PERISSION;
        }
        repository.delete(chapter);
        return Messages.SUCCESC;

    }


}
